package cn.ac.iscas.service.transformer;

import cn.ac.iscas.base.utils.ParameterUtils;
import cn.ac.iscas.base.utils.SpringUtil;
import cn.ac.iscas.domain.source.FlinkSourceColumn;
import cn.ac.iscas.service.queue.flink.FlinkTableQueueService;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author LJian
 * @version 1.0
 * @description: TODO
 * @date 2022/11/24 9:45
 */
public class CleanNullTransformer {
    private final static String ID = "null_data_clean_trans";
    private final static String COLUMN_KEY = "column";

    private String jobId;
    private String componentId;
    private String frontTableName;
    private List<FlinkSourceColumn> frontColumns;

    private String currentTableName;
    private List<FlinkSourceColumn> currentColumns;

    public CleanNullTransformer(String jobId, String taskId) {
        this.jobId = jobId;
        this.componentId = taskId;
    }

    public CleanNullTransformer(String jobId, String taskId, String frontTableName, List<FlinkSourceColumn> frontColumns) {
        this.jobId = jobId;
        this.componentId = taskId;
        this.frontTableName = frontTableName;
        this.frontColumns = frontColumns;
        this.currentColumns = frontColumns;
    }


    public CleanNullTransformer() {

    }

    //CREATE VIEW c11ddebe.c11ddebe.clean AS ( SELECT * FROM c389ec0f.c389ec0f.ods_deduplication_writer WHERE interest IS NOT NULL; );
    public String getSql(Map<String, Object> parameters) {
        this.currentTableName = String.format("%s.%s.%s_%s", jobId, jobId, ID, UUID.randomUUID().toString().substring(0,6));
        String createViewSql = String.format("CREATE VIEW %s AS ", this.currentTableName);
        String column = ParameterUtils.getRequiredString(parameters, COLUMN_KEY);
        String selectSql = String.format("( SELECT * FROM %s WHERE %s IS NOT NULL)", frontTableName, column);
        createViewSql += selectSql;


        updateSource();
        return createViewSql;
    }

    public void updateSource() {
        FlinkTableQueueService flinkTableQueueService = SpringUtil.getBean(FlinkTableQueueService.class);
        Map<String, List<FlinkSourceColumn>> tableColumns = new ConcurrentHashMap<>(8);
        tableColumns.put(this.currentTableName, this.currentColumns);
        flinkTableQueueService.put(this.jobId, this.componentId, tableColumns);
    }
}
